package com.teach.commons;

import java.io.Reader;
import java.util.function.Supplier;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyBatisUtil {
	
	private static Logger log = LoggerFactory.getLogger(MyBatisUtil.class);
	private static SqlSessionFactory ssf;
	
	private static ThreadLocal<SqlSession> local;
	
	
	static {
		try {
			String resourse = "mybatis-config.xml";
			Reader reader = null;
			// 加载配置文件，创建会话工厂
			reader = Resources.getResourceAsReader(resourse);
			ssf = new SqlSessionFactoryBuilder().build(reader);
//			local = ThreadLocal.withInitial(new Supplier<SqlSession>() {
//
//				@Override
//				public SqlSession get() {
//					
//					return ssf.openSession();
//				}
//			});
			local = ThreadLocal.withInitial(()->{return ssf.openSession();});//lambda表达式 jdk1.8+
			
		}catch (Exception e) {
			log.error("创建MyBatis会话工厂失败",e);
			System.exit(0);
		}
	}

	private MyBatisUtil() {
	}
	
	public static SqlSession getSession() {
		log.debug("获取MyBatis会话");
		return local.get();
	}

	public static <T> T getMapper(Class<T> type) {
		log.debug("获取Mapper:"+type.getName());
		return getSession().getMapper(type);
	}

	public static void rollback() {
		local.get().rollback();
		log.debug("会话回滚");
	}

	public static void commit() {
		local.get().commit();
		log.debug("会话提交");
	}

	public static void close() {
		local.get().close();
		local.remove();
		log.debug("会话关闭");
	}

}
